package com.lancoo.answer.view.fragment.composition.answer;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ivan.EasyImageSelect;
import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.ivan.easyphotos.models.album.entity.Photo;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.ConfirmDialogHelper;
import com.lancoo.answer.helper.LoadDialogHelper;
import com.lancoo.answer.helper.PictureRecognitionHelper;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.ImgRecognitionCollectionBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.ImageCallBackEventBean;
import com.lancoo.answer.model.eventBean.ImageEventBean;
import com.lancoo.answer.util.EditTextInputUtil;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.view.fragment.composition.adapter.ImageAdapter;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/8 14:15
 * Description:
 */
public class CompositionPictureAnswerFragmentCopy extends Fragment implements View.OnClickListener{

    private static final String TAG = "CompositionPictureAnswe";
    private Item item;
    private ImageAdapter mAdapter;
    private List<String> showImgList;
    private int typeIndex =-1;
    private int quesIndex =-1;
    private int childIndex =-1;
    private int itemIndex =-1;
    private AlertDialog loadDialog;
    private View convertView;
    private long subTime;
    private Ques ques;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        convertView = inflater.inflate(R.layout.ev_fragment_composition_answer_type_picture_copy, container, false);
        return convertView;
    }

    public void setItem(Item item) {
        this.item = item;
    }


    public static Fragment loadFragment(int typeIndex, int queseIndex, int childIndex,int itemIndex){
        Log.e(TAG,"pic loadFragment itemIndex:"+itemIndex);
        CompositionPictureAnswerFragmentCopy fragment=new CompositionPictureAnswerFragmentCopy();
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX,childIndex);
        mBundle.putInt(AnswerConstant.KEY_ITEMINDEX,itemIndex);
        fragment.setArguments(mBundle);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initView(View view){
        Log.e("aaaa","图片作答初始化view");
        EventBus.getDefault().register(this);
        if(getArguments()==null){
            return;
        }
        showImgList=new ArrayList<>();
        typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        itemIndex = getArguments().getInt(AnswerConstant.KEY_ITEMINDEX);
        Log.e(TAG,"pic  initView:"+itemIndex);
        final TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if(constantExamBean==null){
            return;
        }
        if(taskControlBean==null){
            return;
        }
        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(typeList==null){
            return;
        }
        Type type = typeList.get(typeIndex);
        if(type==null){
            return;
        }
        List<Ques> quesList = type.getQuesList();
        if(quesList==null){
            return;
        }
        ques = quesList.get(quesIndex);
        if(ques==null){
            return;
        }
        List<Child> childList = ques.getChildList();
        if(childList==null){
            return;
        }
        Child child = childList.get(childIndex);
        if(child==null||child.getItemList()==null){
            return;
        }
        item = child.getItemList().get(itemIndex);
        updateRecognitionStyle();
        EditText edittext = convertView.findViewById(R.id.edittext);
        if(TextUtils.isEmpty(item.getImgRecognitionTxt())){
            item.setImgRecognitionTxt("");
        }
        edittext.setText(item.getImgRecognitionTxt());
        edittext.setSelection(edittext.getText().length());
        convertView.findViewById(R.id.tv_clear_txt).setOnClickListener(this);
        EditTextInputUtil.disableCopyAndPaste(edittext);
        SoftInputUtils.setEditTextInputSpace(edittext);
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                item.setImgRecognitionTxt(s.toString().trim());
                if(convertView !=null){
                    edittext.requestLayout();
                }
                updateAnswerCount();
            }
        });
        RecyclerView mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
        List<String> imagePath = item.getImagePathList();
        if(imagePath==null||imagePath.size()==0||imagePath.get(0)==null){
            List<String> list=new ArrayList<>();
            item.setImagePathList(list);
        }else{
            showImgList.addAll(item.getImagePathList());
        }
        mAdapter = new ImageAdapter(showImgList,0);
        mAdapter.setImageOperateCallBack(new ImageAdapter.ImageOperateCallBack() {

            @Override
            public void gotoImageLibChoice() {
                startImageViewChoice();
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void deletChoiceImage(int position){
                showImgList.remove(position);
                if(mAdapter!=null){
                    mAdapter.notifyDataSetChanged();
                }
                item.setImagePathList(showImgList);
                int trainSence =taskControlBean.getTrainSence();
                if(trainSence==0){
                    item.setImgRecognitionTxt("");
                }
                updateRecognitionStyle();
                ImageEventBean imageEventBean=new ImageEventBean();
                imageEventBean.setTypeIndex(typeIndex);
                imageEventBean.setQueseIndex(quesIndex);
                imageEventBean.setChildIndex(childIndex);
                imageEventBean.setItemIndex(itemIndex);
                imageEventBean.setOperateType(1);
                imageEventBean.setPosition(position);
                Log.e("eee","外部开始图片上传"+new Gson().toJson(imageEventBean));
                EventBus.getDefault().post(imageEventBean);
            }

            @Override
            public void lookChoiceImage(int position){
                EasyPhotos.startPreviewPaths(getActivity(), GlideEngine.getInstance(),
                        showImgList,true,position);
            }

        });
        mRecyclerView.setAdapter(mAdapter);
    }


    private void startImageViewChoice(){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        final int trainSence =taskControlBean.getTrainSence();
        Log.e("aaaa","当前模式："+trainSence);
        int MAX_SIZE_IMG = 3;
        EasyImageSelect.withImage(getActivity())
                .setNeedCompress(true)
                .setNeedRecognite(true)
                .setUseCustomCamera(true)
                .setOnlyCapture(taskControlBean.getTrainSence()!=0)
                .setMaxImageNumber(MAX_SIZE_IMG -showImgList.size())
                .setRecognitionEngine((context, photos, callback) ->
                        PictureRecognitionHelper.startPictureRecognition(context,photos,callback,item))
                .setCallBack(new EasyImageSelect.ImageSelectCallBack() {
                    @Override
                    public void onImageSelectResult(List<String> imgList, List<Photo> photos) {
                        Log.e("choice img","获取图片回来");
                        upLoadImgFiles(imgList);
                        if(trainSence!=0){
                            updateRecognitionStyle();
                            updateRecognitionContent();

                        }
                    }

                    @Override
                    public void onDismiss() {

                    }
                }).show();
    }

    private List<String> tempImgList;
    private void upLoadImgFiles(List<String> imgList){
        tempImgList=imgList;
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        int mediaAnswerSaveType = taskControlBean.getMediaAnswerSaveType();
        ImageEventBean imageEventBean=new ImageEventBean();
        imageEventBean.setTypeIndex(typeIndex);
        imageEventBean.setQueseIndex(quesIndex);
        imageEventBean.setChildIndex(childIndex);
        imageEventBean.setChildIndex(itemIndex);
        if(item.getImagePathList()==null){
            imageEventBean.setPosition(0);
        }else{
            imageEventBean.setPosition(item.getImagePathList().size());
        }
        imageEventBean.setImgList(imgList);
        EventBus.getDefault().post(imageEventBean);
        if(mediaAnswerSaveType==0){
            ImageCallBackEventBean bean=new ImageCallBackEventBean();
            bean.setSuccess(true);
            bean.setTypeIndex(typeIndex);
            bean.setChildIndex(childIndex);
            bean.setQueseIndex(quesIndex);
            bean.setItemIndex(itemIndex);
            bean.setImgList(imgList);
            onImageEventCallBack(bean);
            return;
        }
        loadDialog = LoadDialogHelper.showLoadDialog(getContext(), R.string.ev_uploading,false);
        for (String path:imgList){
            Log.e("aaa","收到图片："+ path);
        }
    }


    /**
     * 图片上传
     */
    //
    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImageEventCallBack(final ImageCallBackEventBean callBackEventBean) {
        Log.e(TAG,"图片上传执行结果回调");
        if(callBackEventBean.getTypeIndex()== typeIndex &&
                callBackEventBean.getQueseIndex()== quesIndex &&
                callBackEventBean.getChildIndex()== childIndex&&
                callBackEventBean.getItemIndex()==itemIndex){
            List<String> imgList = callBackEventBean.getImgList();
            if(loadDialog!=null&&loadDialog.isShowing()){
                loadDialog.dismiss();
            }
            if(imgList!=null&&imgList.size()>0){
                Log.e("aaa","回调："+imgList.get(0));
                showImgList.addAll(imgList);
                item.setImagePathList(showImgList);
                List<ImgRecognitionCollectionBean> list=new ArrayList<>();
                if(item.getImagePathList()==null){
                    item.setImagePathList(new ArrayList<>());
                }
                if(tempImgList.size()==item.getImagePathList().size()){
                    for (String s:tempImgList){
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(s);
                        list.add(bean);
                    }
                }else{
                    for (int i = 0; i < item.getImagePathList().size()-tempImgList.size(); i++) {
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(item.getImagePathList().get(i));
                        list.add(bean);
                    }
                    for (String s:tempImgList){
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(s);
                        list.add(bean);
                    }
                }
                item.setImgRecognitionDataList(list);

                if(mAdapter!=null)
                    mAdapter.notifyDataSetChanged();
            }else{
                showImgUploadFailureDialog();

            }
        }
    }

    /**
     * 重新上传图片作答
     */
    private void showImgUploadFailureDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 2,
                getString(R.string.ev_picture_upload_failure), getString(R.string.ev_upload_retry),
                getString(R.string.ev_cancel), new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        if(tempImgList==null||tempImgList.size()==0){
                            return;
                        }
                        upLoadImgFiles(tempImgList);

                    }
                });
    }


    public void updateKeyboardShowState(boolean isShow){
        if(convertView!=null){
            convertView.findViewById(R.id.recyclerView).setVisibility(isShow?View.GONE:View.VISIBLE);
        }
        updateRecognitionStyle();
    }

    /**
     * 识别内容有修改，界面样式有更新
     */
    private void updateRecognitionStyle(){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null||taskControlBean.getTrainSence()==0){
            return;
        }
        boolean isEmptyAnswer= item.getImagePathList() == null || item.getImagePathList().size() <= 0;
        if(!TextUtils.isEmpty(item.getImgRecognitionTxt())){
            isEmptyAnswer=false;
        }
        if(isEmptyAnswer){
            convertView.findViewById(R.id.tv_picture_answer_alert).setVisibility(View.VISIBLE);
            convertView.findViewById(R.id.tv_answer_count).setVisibility(View.GONE);
            convertView.findViewById(R.id.edittext).setVisibility(View.GONE);
            convertView.findViewById(R.id.ll_clear_txt).setVisibility(View.GONE);
            convertView.findViewById(R.id.view_12dp).setVisibility(View.GONE);
        }else{
            convertView.findViewById(R.id.tv_picture_answer_alert).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_answer_count).setVisibility(View.VISIBLE);
            convertView.findViewById(R.id.edittext).setVisibility(View.VISIBLE);
//            convertView.findViewById(R.id.ll_edittext).setVisibility(View.VISIBLE);
            convertView.findViewById(R.id.ll_clear_txt).setVisibility(View.VISIBLE);
            convertView.findViewById(R.id.view_12dp).setVisibility(View.VISIBLE);
            if(ques==null||!TextUtils.equals("W",ques.getTypeNo())){
                //如果不是听写题，后续不用处理
                return;
            }
            convertView.findViewById(R.id.tv_answer_count).setVisibility(View.GONE);
            convertView.findViewById(R.id.ll_clear_txt).setVisibility(View.GONE);
            convertView.findViewById(R.id.edittext).setBackgroundResource(R.drawable.ev_shape_3_corners_f7_bg);
        }
    }


    /**
     *更新识别内容
     */
    private void updateRecognitionContent(){
        if(convertView==null){
            return;
        }
        EditText edittext = convertView.findViewById(R.id.edittext);
        edittext.setText(item.getImgRecognitionTxt());
        edittext.setSelection(edittext.getText().length());
        edittext.requestLayout();
    }

    /**
     * 统计作答个数
     */
    private void updateAnswerCount(){
        if(convertView==null){
            return;
        }
        TextView tv_answerCount=convertView.findViewById(R.id.tv_answer_count);

        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    int count=0;
                    if(!TextUtils.isEmpty(item.getImgRecognitionTxt())){
                        String[] split = item.getImgRecognitionTxt()
                                .replace("\n"," ")
                                .split(" ");
                        count=split.length;
                        for (String str : split) {
                            if (str.isEmpty()) {
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count,0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(integer -> {

                    SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString=new SpannableString(""+integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666),0,spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    tv_answerCount.setText(spannableStringBuilder);
                }, throwable -> {});
    }

    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-subTime<500){
            return;
        }
        subTime=System.currentTimeMillis();
        int id=v.getId();
        if(id==R.id.tv_clear_txt){
            showClearTxtConfigDialog();
        }
    }

    /**
     *  清空文本确认弹窗
     */
    private void showClearTxtConfigDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 1, "温馨提示",
                "您确认清空文本吗？", "确定", "取消", new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        item.setImgRecognitionTxt("");
                        updateRecognitionContent();
                        updateAnswerCount();
                        updateRecognitionStyle();
                        if(getActivity()==null){
                            return;
                        }
                        SoftInputUtils.hideSoftInput(getActivity());
                    }
                });

    }


}
